#!/usr/bin/python

'''
console.py

Copyright 2009 Xavier Mendez Navarro aka Javi

This file is part of pysqlin

pysqlin is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation version 2 of the License.

pysqlin is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with pysqlin; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
'''

import logging
import sys

from ui.console import Console
from framework.controller import ConsoleController
from framework.settings import Settings
from framework.facade import Facade
from framework.myexceptions import MyException


# logging system

debuglevel = Settings().get(Settings.SEC_GRL, Settings.DEBUG_LEVEL)

if debuglevel == Settings.DEBUG_LEVEL_DEBUG:
	level = logging.DEBUG
elif debuglevel == Settings.DEBUG_LEVEL_INFO:
	level = logging.INFO
elif debuglevel == Settings.DEBUG_LEVEL_WARNING:
	level = logging.WARNING
elif debuglevel == Settings.DEBUG_LEVEL_ERROR:
	level = logging.ERROR
elif debuglevel == Settings.DEBUG_LEVEL_CRITICAL:
	level = logging.CRITICAL

logging.basicConfig(level = level,
		    format = '%(asctime)s %(name)-12s %(levelname)-8s %(message)s',
		    datefmt = '%m-%d %H:%M',
		    filename = Settings().get(Settings.SEC_GRL, Settings.LOGFILE),
		    filemode = 'a')

## define a Handler which writes INFO messages or higher to the sys.stderr
#console = logging.StreamHandler()
#console.setLevel(logging.DEBUG)
#
## set a format which is simpler for console use
#formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
## tell the handler to use this format
#console.setFormatter(formatter)
## add the handler to the root logger
#logging.getLogger('').addHandler(console)

logger = logging.getLogger("pysqlin")

logger.info('-------------------------------------------------------------------')
logger.info('Starting pysqlin...')
logger.info('-------------------------------------------------------------------')


# new console
try:
    view = Console("pysqlin", 'commands.xml')
except MyException:
    print "Fatal error initializing console, check commands.xml"
    sys.exit(1)

controller = ConsoleController(view)
Facade().startup(view, controller)

# main console loop
view.run()

